<template>
  <div :id="id">
    <Portal to="right-disable"
            :disabled="!queryModelDefaultSetting.showSetting">
      <el-card shadow="never" v-loading="loading"
               :style="{height: gadgetHeight + 'px',border:0}"
               class="aui-card--fill">
        <div>
          <div class="cardHeader"
               @mouseenter="mouseenter(true)"
               @mouseleave="mouseenter(false)"
               v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
            <span>
              <span class="cardTitle threepoints"
                    :title="widgetName"
                    v-if='widgetName && widgetName.trim().length>0'>{{ widgetName }}</span>
              <el-tooltip :open-delay="1000" class="item"
                          effect="dark"
                          :content="gadgetSetting.headerDescription"
                          placement="right"
                          v-if='gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0'>
                <i class="cuifont icon_help_circle cardIcon"></i>
              </el-tooltip>
            </span>
            <MoreMenu :slicer='slicer' :gadgetId='id'
                      :gadgetType='gadgetInfo.com'
                      @updateQuery="query"
                      @fullScreen="fullScreen" />
          </div>
          <div class="control-section">
            <div class="content-wrapper">
              <ejs-accumulationchart v-if="isHasData"
                                     ref='piechart'
                                     :theme='gadgetSetting.theme'
                                     :style="{height: gadgetHeight-10 + 'px'}"
                                     align='center'
                                     :width='chartWidth'
                                     :title='gadgetSetting.title'
                                     :legendSettings='gadgetSetting.legendSettings'
                                     :tooltip='gadgetSetting.tooltip'
                                     enableSmartLables='true'
                                     :enableAnimation='gadgetSetting.enableAnimation'
                                     :center='gadgetSetting.center'
                                     :pointClick="onClick">
                <e-accumulation-series-collection>
                  <e-accumulation-series :dataSource='dataSource'
                                         :startAngle='gadgetSetting.startAngle'
                                         :endAngle='gadgetSetting.endAngle'
                                         :explodeOffset='gadgetSetting.explodeOffset'
                                         :explodeIndex='gadgetSetting.explodeIndex'
                                         :radius='gadgetSetting.radius'
                                         :xName='gadgetSetting.valueFieldsNameMeasureX'
                                         :yName='gadgetSetting.valueFieldsNameMeasureY'
                                         :dataLabel='gadgetSetting.dataLabel'
                                         :name='gadgetSetting.name'
                                         innerRadius='0%'
                                         explode='true'>
                  </e-accumulation-series>
                </e-accumulation-series-collection>
              </ejs-accumulationchart>
              <div v-else
                   class="gadget-no-data">
                <el-image @click="query()"
                          :src='noDataImageUrl'
                          fit='fill'></el-image>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      <Lastupdatetime v-if="currentTime" :currentTime="currentTime"></Lastupdatetime>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
      <div style="position:absolute;left:9999px;">
        <component v-for="(item, index) in formatComponentList"
                  :key="index"
                  :is="item"
                  :ref="item"
                  gadgetType='notgridgadget' />
      </div>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
// import model from '@/components/gadget/query-model/query-model.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'

import mixinFormatViewModule from '@/mixins/format-gadget-view-module'

export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      currentTime: null,
      theme: 'Material',
      dataSource: [],
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'piechartgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'piechartgadget' }).gadgetSetting
          // gadgetSetting: {
          //   theme: 'Material',
          //   title: '',
          //   valueFieldsNameMeasureX: 'x',
          //   valueFieldsNameMeasureY: 'y',
          //   valueFieldsNameMeasureText: 'text',
          //   legendSettings: {
          //     visible: false
          //   },
          //   tooltip: {
          //     enable: true,
          //     format: '$' + `{point.x} : <b>$` + `{point.y}</b>`
          //   },
          //   enableAnimation: false,
          //   center: { x: '50%', y: '50%' },
          //   startAngle: '0',
          //   endAngle: '360',
          //   radius: '70%',
          //   explodeOffset: '10%',
          //   explodeIndex: 0,
          //   dataLabel: {
          //     visible: true,
          //     position: 'Inside',
          //     name: 'text',
          //     font: {
          //       fontWeight: '600'
          //     }
          //   },
          //   headerTitle: '',
          //   headerDescription: ''
          // }
        }
      },
      queryId: '',
      queryDrillthrough: {},
      widgetName: ''
    }
  },

  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    this.query()
    this.subscribeMessage('runReport', this.query)
    this.$store.state.isWidget = false
  },
  updated () {
    // this.$nextTick(() => {
    //   if (this.$refs.piechart) {
    //     this.$refs.piechart.ej2Instances.refresh()
    //     this.$refs.piechart.ej2Instances.removeSvg()
    //     this.$refs.piechart.ej2Instances.refreshSeries()
    //     this.$refs.piechart.ej2Instances.refreshChart()
    //   }
    // })
  },
  methods: {
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 45
      this.gadgetWidth = newWPx
      this.chartWidth = (newWPx - 10) + 'px'
    },
    onClick (e) {
      var pointx = ''
      var isTrim = false
      if (!e.point) {
        e.point = {}
        pointx = e.series.dataSource[e.pointIndex][e.series.xName]
      } else {
        pointx = e.point.x
      }
      if (pointx === 'Null' || pointx === null) {
        pointx = ' is null'
      } else if (pointx === ' ') {
        isTrim = true
        pointx = "= ''"
      } else {
        pointx = "= '" + pointx + "'"
      }
      // e.point.x: 1
      // e.point.y: 5
      // e.series.xName: "status"
      // e.series.yName:'id'
      // e.point.text: "Data Analyst"
      // let data = '"' + e.series.xName + '"' + "='" + e.point.x + "'"
      // this.findOriginData(data)
      let data = ''
      if (this.queryDrillthrough.queryId) {
        if (isTrim) {
          data = 'trim("' + (this.queryDrillthrough.field ? this.queryDrillthrough.field : this.queryDrillthrough.columnName) + '")' + pointx
        } else {
          data = '"' + (this.queryDrillthrough.field ? this.queryDrillthrough.field : this.queryDrillthrough.columnName) + '"' + pointx
        }
      }
      this.findOriginData(data)
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 10) + 'px'
    },
    query () {
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      this.loading = true
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        this.currentTime = new Date()
        _self.verifyHasData(res)
        // Set y column type is Number or 0
        if (res.config) {
          _self._.merge(_self.gadgetSetting, res.config)
        }
        if (res.name) {
          _self.widgetName = res.name
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        this.setComponentList(res.selectFields)
        this.$nextTick(() => {
        // let tempList = res.data
          let tempList = this.chartLabelFormat(res.data, res.selectFields)
          let sum = 0
          for (let i = 0; i < tempList.length; i++) {
            if (res.config.valueFieldsNameMeasureY) {
              tempList[i][res.config.valueFieldsNameMeasureY] = Number(tempList[i][res.config.valueFieldsNameMeasureY]) ? Number(tempList[i][res.config.valueFieldsNameMeasureY]) : 0
              tempList[i].rateDataLabel = tempList[i][res.config.valueFieldsNameMeasureX] + ': #RATE#' + ' (' + tempList[i][res.config.valueFieldsNameMeasureY] + ')'
              sum += tempList[i][res.config.valueFieldsNameMeasureY]
            } else if (tempList[i].y) {
              tempList[i].y = Number(tempList[i].y) ? Number(tempList[i].y) : 0
              tempList[i].rateDataLabel = tempList[i][res.config.valueFieldsNameMeasureX] + ': #RATE#' + ' (' + tempList[i].y + ')'
              sum += tempList[i].y
            }
          }

          for (let i = 0; i < tempList.length; i++) {
            let temp = res.config.valueFieldsNameMeasureY ? tempList[i][res.config.valueFieldsNameMeasureY] : tempList[i].y
            let rate = (+(temp / sum * 100).toFixed(2))
            tempList[i].rateDataLabel = tempList[i].rateDataLabel.replace('#RATE#', rate + '%')
          }

          _self.dataSource = tempList
          // _self.dataSource = this.chartLabelFormat(tempList, res.selectFields)
          let objList = res.selectFields.find(item => { return item.dataType === 'dimension' })
          _self.queryDrillthrough = objList || {}
          _self.queryId = _self.queryDrillthrough ? _self.queryDrillthrough.queryId : ''
          _self.gadgetSetting.dataLabel.name = 'rateDataLabel'
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    chartLabelFormat (data, fieldsList) {
      let temp = data.map(item => {
        for (const key in item) {
          let fieldItemIndex = fieldsList.findIndex(e => e['alias'] === key)
          fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['dataType'] === 'dimension'))
          fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['alias'] === 'dimension1'))
          if (fieldItemIndex === -1) {
            continue
          }
          let fieldType = fieldsList[fieldItemIndex]['businessType']
          if (this.gadgetSetting.valueFieldsNameMeasureY !== key && (fieldType === 'date' || fieldType === 'datetime')) {
            let templateName = this.getFormatTemplateName(fieldsList, key)
            item[key] = this.getFormatData(item[key], templateName) || item[key]
          }
        }
        return item
      })
      return temp
    },
    getFormatData (value, templateName) {
      try {
        return this.$refs[templateName][0].format(value)
      } catch (error) {
        return value
      }
    },
    setComponentList (fieldsList) {
      let temp = []
      fieldsList.map(e => {
        let name = this.findTemplateName(e['fieldsFormat'], e['businessType'])
        name && temp.push(name)
      })
      this.formatComponentList = this._.uniq(temp)
    }
  }
})
</script>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
